<template>
  <div
    class="page_body"
    v-loading.fullscreen.lock="loadingKey"
    :element-loading-text="loadingText"
  >
    <el-row>
      <div class="department_manager_content">
        <!-- 按钮栏 -->

        <!-- 数据列表 -->
        <div
          v-if="
            departmentListData != undefined && departmentListData.length > 0
          "
        >
          <el-row>
            <el-col :span="24">
              <el-table
                :data="departmentListData"
                border
                size="mini"
                style="width: 100%"
                >admin/department/index
                <el-table-column
                  prop="department_name"
                  label="部门"
                  align="center"
                  min-width="180"
                >
                </el-table-column>

                <el-table-column label="操作" min-width="200" align="center">
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="primary"
                      @click="uploadListFn(scope.$index, scope.row)"
                      >导入名单</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <div class="department_manager_pagination">
                <el-pagination
                  @size-change="listSizeChange"
                  @current-change="listCurrentChange"
                  :current-page="currentPage"
                  :page-sizes="pageSizes"
                  :page-size="pageSize"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="total"
                >
                </el-pagination>
              </div>
            </el-col>
          </el-row>
        </div>
        <el-row v-else>
          <el-empty description="暂无数据"></el-empty>
        </el-row>

        <!-- 导入名单弹窗 -->
        <el-dialog
          title="导入名单"
          :visible.sync="uploadDalogVisible"
          :close-on-click-modal="false"
          width="400px"
          :modal="false"
        >
          <el-upload
            ref="uploadListRef"
            class="upload-demo"
            :action="actionUrl"
            :headers="headers"
            :data="uploadFileData"
            :name="fileName"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :file-list="fileList"
            multiple
          >
            <el-button slot="trigger" size="small" type="primary"
              >上传文件</el-button
            >
            <div slot="tip" class="el-upload__tip">
              选择名单xlsx文件或图片png/jpg文件上传
            </div>
          </el-upload>

          <span slot="footer" class="dialog-footer">
            <el-button
              size="small"
              type="primary"
              @click="downloadTemplate(qrcodeUrl)"
              >下载模板</el-button
            >
            <el-button size="small" @click="uploadDialogclose()"
              >关 闭</el-button
            >
          </span>
        </el-dialog>
      </div>
    </el-row>
  </div>
</template>
<style src="../../assets/css/match/matchBindDepartment.css" scoped></style>

<script>
export default {
  name: "MatchBindDepartment",
  components: {},
  props: {
    matchId: {
      type: Number,
    },
  },
  data() {
    return {
      userType: this.$store.state.loginUserType == "ADMINLOGINUSERCH" ? 0 : 1, // 用户类型;1. 普通; 0. 超级;
      baseAPIUrl: this.$store.state.baseAPIUrl,
      //   matchId: "", // 赛事名称id
      matchtitle: "", // 赛事名称名称
      qrcodeUrl: "", // 二维码链接
      departmentListData: [], // 数据列表
      currentPage: 1, // 当前页
      pageSizes: [10, 20, 50, 100], // 可选页容量
      pageSize: 10, // 当前页容量
      total: 0, // 总条数
      searchKey: "", // 搜索关键词
      loadingKey: false,
      loadingText: "",
      dialogVisible: false, // 弹窗显示
      detailFormData: {
        departmentSelect: [],
      }, // 部门弹窗数据
      formLabelWidth: "90px",
      selectLoading: false,
      userListData: [], // 用户列表数据
      managerData: {
        id: "",
        leaderList: [],
        assistantList: [],
      },
      addUserData: {
        addUserId: "",
        addRole: null,
      },
      addUserIdLabelWidth: "70px",

      departmentSelectList: [],
      uploadDalogVisible: false, // 导入文件弹窗显示
      actionUrl: "",
      headers: {
        Authorization: this.$store.state.loginToken,
      }, // 导入headers
      uploadData: {
        event_id: "",
        department_id: "",
      }, // 导入参数
      uploadFileData: {}, // 导入组件参数
      fileName: "",
      fileList: [],

      department_id: "", //下载模板的部门id
    };
  },
  created: function () {
    console.log(this.matchId);
    this.getListDataFn();
    this.getDepartmentList();
    this.getUserListDataFn();
  },
  methods: {
    // 获取列表数据
    getListDataFn: function () {
      let that = this;
      console.log(this.matchId);
      let url = "/admin/eventdepartment/index";
      let data = {
        event_id: this.matchId,
        page: this.currentPage,
        perPage: this.pageSize,
      };
      that.loadingText = "加载中...";
      that.loadingKey = true;
      this.axios
        .post(url, data)
        .then((response) => {
          that.loadingKey = false;
          if (response.code == 0) {
            that.matchtitle = response.event.title;
            that.departmentListData = response.list;
            that.total = response.total_count;
          } else {
            that.$message.error(response.msg);
          }
        })
        .catch(function (error) {
          that.loadingKey = false;
          console.log(error);
        });
    },
    // 获取部门数据
    getDepartmentList: function () {
      let that = this;
      let url = "/admin/department/index";
      let data = {};
      that.loadingText = "加载中...";
      that.loadingKey = true;
      this.axios
        .post(url, data)
        .then((response) => {
          that.loadingKey = false;
          if (response.code == 0) {
            that.departmentSelectList = response.list;
          } else {
            that.$message.error(response.msg);
          }
        })
        .catch(function (error) {
          that.loadingKey = false;
          console.log(error);
        });
    },
    // 获取用户列表数据
    getUserListDataFn: function (query) {
      let that = this;
      let url = "/admin/adminusers/index";
      let data = {
        keywords: "",
      };
      if (query) {
        data = {
          keywords: query,
        };
      }
      this.axios
        .post(url, data)
        .then((response) => {
          that.selectLoading = false;
          if (response.code == 0) {
            that.userListData = response.list;
          } else {
            that.$message.error(response.msg);
          }
        })
        .catch(function (error) {
          that.selectLoading = false;
          console.log(error);
        });
    },
    // 关闭导入弹窗
    uploadDialogclose: function () {
      this.uploadDalogVisible = false;
    },

    // 导入名单
    uploadListFn: function (index, row) {
      let that = this;

      let department_id = row.department_id;
      this.department_id = row.department_id;
      console.log(department_id, row, this.department_id);
      this.uploadData = {
        event_id: this.matchId,
        department_id: department_id,
      };
      this.uploadDalogVisible = true;
      this.$nextTick(() => {
        that.$refs.uploadListRef.clearFiles();
      });
    },

    // 下载模板
    downloadTemplate: function () {
      let that = this;
      let url = "/excel/exportEventTemplateTwo";
      let data = {
        event_id: this.matchId,
        department_id: this.department_id,
      };

      that.loadingText = "处理中...";
      that.loadingKey = true;
      that.axios
        .post(url, data)
        // { responseType: "blob" }
        .then((response) => {
          that.loadingKey = false;
          if (response.code == 1) {
            that.$message.error(response.msg);
            this.uploadDalogVisible = false;
          } else {
            let blob = new Blob([response], {
              type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
            });
            const link = document.createElement("a");
            // link.href = URL.createObjectURL(blob);
            // link.download = "event_import.xlsx";
            link.href = response.file;
            // document.body.appendChild(link);
            link.click();
            // window.URL.revokeObjectURL(link.href);
            // document.body.removeChild(link);
            this.uploadDalogVisible = false;
          }
        })
        .catch(function (error) {
          that.loadingKey = false;
          console.log(error);
        });
    },

    // 上传成功钩子
    handleAvatarSuccess: function (res) {
      if (res.code == 1) {
        this.$message.error(res.msg);
      } else {
        this.$message.success("导入成功");
      }
    },
    // 上传前钩子
    beforeAvatarUpload: function (file) {
      let that = this;
      let type = file.name.indexOf(".xlsx");
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 10;

      if (type == -1 && !isJPG && !isPNG) {
        this.$message.error("上传xlsx/jpg/png文件");
        resolve(false);
      }
      if (isJPG || isPNG) {
        if (!isLt2M) {
          this.$message.error("上传图片大小不能超过 10MB!");
          resolve(false);
        }
      }
      return new Promise((resolve, reject) => {
        let type = file.name.indexOf(".xlsx");
        const isJPG = file.type === "image/jpeg";
        const isPNG = file.type === "image/png";
        const isLt2M = file.size / 1024 / 1024 < 3;

        if (type != -1) {
          let dataObj = JSON.parse(JSON.stringify(this.uploadData));
          this.$set(
            that,
            "actionUrl",
            this.$store.state.baseAPIUrl + "/excel/importApply"
          );
          this.$set(that, "uploadFileData", dataObj);
          this.$set(that, "fileName", "excelfile");
          this.$nextTick(() => {
            resolve(true);
          });
        } else {
          let obj = {
            event_id: this.matchId,
            department_id: this.department_id,
          };
          this.$set(
            that,
            "actionUrl",
            this.$store.state.baseAPIUrl + "/upload/uploadPhotoFile"
          );
          this.$set(that, "uploadFileData", obj);
          this.$set(that, "fileName", "file");
          this.$nextTick(() => {
            resolve(true);
          });
        }
      });
    },

    // 复制文本
    copy: function (data) {
      let OrderNumber = data;
      // 创建一个input 元素
      let newInput = document.createElement("input");
      newInput.value = OrderNumber;
      document.body.appendChild(newInput);
      newInput.select();
      document.execCommand("Copy");
      newInput.remove();
      that.$message.success("复制成功");
    },

    // 页容量改变
    listSizeChange: function (val) {
      this.currentPage = 1;
      this.pageSize = val;
      this.getListDataFn();
    },
    // 当前页改变
    listCurrentChange: function (val) {
      this.currentPage = val;
      this.getListDataFn();
    },
    // 搜索按钮
    searchFn: function () {
      this.currentPage = 1;
      this.getListDataFn();
    },
    // 成员选择搜索
    remoteMethod: function (query) {
      if (query !== "") {
        this.selectLoading = true;
        this.getUserListDataFn(query);
      } else {
        this.selectLoading = true;
        this.getUserListDataFn();
      }
    },
    // 添加成员
    addUserFn: function () {
      let that = this;
      let url = "/admin/eventdepartment/addManager";
      let data = {
        event_department_id: this.managerData.id,
        admin_userid: this.addUserData.addUserId,
        role: this.addUserData.addRole,
      };
      this.$refs.addUserForm.validate((valid) => {
        if (!valid) {
          return false;
        } else {
          that.loadingText = "处理中...";
          that.loadingKey = true;
          that.axios
            .post(url, data)
            .then((response) => {
              that.loadingKey = false;
              if (response.code == 0) {
                that.$message.success("添加成功");
                that.getDetailFn(that.managerData.id);
              } else {
                that.$message.error(response.msg);
              }
            })
            .catch(function (error) {
              that.loadingKey = false;
              console.log(error);
            });
        }
      });
    },
    // 移除成员
    removeUserFn: function (value) {
      let that = this;
      this.$confirm("确认移除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(() => {
          let url = "/admin/eventdepartment/deleteManager";
          let data = {
            id: value,
          };
          that.loadingText = "处理中...";
          that.loadingKey = true;
          that.axios
            .post(url, data)
            .then((response) => {
              that.loadingKey = false;
              if (response.code == 0) {
                that.$message.success("移除成功");
                that.getDetailFn(that.managerData.id);
              } else {
                that.$message.error(response.msg);
              }
            })
            .catch(function (error) {
              that.loadingKey = false;
              console.log(error);
            });
        })
        .catch(() => {});
    },
    // 活动详情
    matchDetail: function () {
      const routeUrl = this.$router.resolve({
        name: "MatchFrom",
      });
      window.open(routeUrl.href + "?id=" + this.matchId + "&key=3", "_blank");
    },
  },
};
</script>
